package com.horse.cloud.framework.general.utils;




import com.horse.cloud.framework.general.enums.ResponseCodeEnums;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : bing.Pan
 * @create : Created by intelliJ IDEA
 * @e-mail : 15923508369@163.com
 * @gmdate : 29/04/2018 21:56
 * @sidesc :
 */

public class EnumUtils {



    /**
     * 根据反射，通过方法名称获取方法值，忽略大小写的
     * @param methodName
     * @param obj
     * @param args
     * @return return value
     */
    private static <T> Object getMethodValue(String methodName, T obj, Object... args) {
        try {
            Method method = obj.getClass().getDeclaredMethod(methodName);
            return  method.invoke(obj, args);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 通过code值获取对应的描述信息
     * @param code
     * @param enumT
     * @param methodNames
     * @param <T>
     * @return
     */
    public static <T> Object getDescriptionByByCode(Object code, Class<T> enumT, String... methodNames) {

        T[] enums = enumT.getEnumConstants();

        for (T obj:enums) {

            Object resultValue = getMethodValue(methodNames[0], obj);
            if (resultValue.toString().equals(code + "")) {
                return getMethodValue(methodNames[1], obj);
            }
        }

        return "";
    }





    /**
     * 枚举转map结合code 作为map的key,description作为map的value
     * @param enumT
     * @param methodNames
     * @param <T>
     * @return
     */
    public static <T> Map<Object, String> EnumToMap(Class<T> enumT, String... methodNames) {
        Map<Object, String> enumMap = new HashMap<Object, String>();
        if (!enumT.isEnum()) {
            return enumMap;
        }
        T[] enums = enumT.getEnumConstants();

        for (int i = 0, len = enums.length; i < len; i++) {
            T obj = enums[i];
            try {
                Object resultValue = getMethodValue(methodNames[0], obj);
                if ("".equals(resultValue)) {
                    continue;
                }
                Object resultDes = getMethodValue(methodNames[1], obj);
                if ("".equals(resultDes)) {
                    resultDes = obj;
                }
                enumMap.put(resultValue, resultDes + "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return enumMap;
    }



    public static void main(String[] args){

        Class<ResponseCodeEnums> clasz= ResponseCodeEnums.class;

        String des=(String) EnumUtils.getDescriptionByByCode(20000,clasz,"getCode","getDescription");
        System.out.println("获取值为20000的描述:"+des);


        Map<Object, String>  map= EnumUtils.EnumToMap(clasz,"getCode","getDescription");
        System.out.println("获取枚举的map集合:"+map);


        System.out.println("获取枚举所有字段:"+ Arrays.toString(ResponseCodeEnums.values()));

    }
}
